package codelib.spring3struts2hibernate3.biz.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import codelib.spring3struts2hibernate3.biz.UserService;
import codelib.spring3struts2hibernate3.dao.UserDAO;
import codelib.spring3struts2hibernate3.dao.model.User;

@Component("UserServiceImpl")
@Transactional
public class UserServiceImpl implements UserService {
	private UserDAO userDAO;

	@Override
	public LoginReturnEnum login(String userName, String password, String lastIp) {
		try {
			Assert.hasLength(userName);
			Assert.hasLength(password);
			Assert.hasLength(lastIp);
		} catch (Throwable e) {
			e.printStackTrace();
			return LoginReturnEnum.FAILED;
		}

		List<User> listUser = this.userDAO.retrieveByName(userName);
		if (listUser == null || listUser.isEmpty()) {
			return LoginReturnEnum.USER_NOT_VALID;
		}

		User user = listUser.get(0);
		if (!password.equals(user.getPassword())) {
			return LoginReturnEnum.PASSWORD_NOT_MATCH;
		}

		user.setCredits(user.getCredits() + 5);
		user.setLastIp(lastIp);
		user.setLastVisit(new Date());
		this.userDAO.update(user);
		return LoginReturnEnum.SUCCESS;
	}

	@Override
	public RegisterReturnEnum register(String userName, String password,
			String lastIp) {
		try {
			Assert.hasLength(userName);
			Assert.hasLength(password);
			Assert.hasLength(lastIp);
		} catch (Throwable e) {
			e.printStackTrace();
			return RegisterReturnEnum.FAILED;
		}

		List<User> listUser = this.userDAO.retrieveByName(userName);
		if (listUser != null && !listUser.isEmpty())
			return RegisterReturnEnum.USER_EXISTS;
		User user = new User();
		user.setUserName(userName);
		user.setPassword(password);
		user.setCredits(20);
		user.setLastVisit(new Date());
		user.setLastIp(lastIp);
		this.userDAO.create(user);
		return RegisterReturnEnum.SUCCESS;
	}

	@Override
	public ResetPasswordrReturnEnum resetPassword(String userName, String password,
			String newPassword) {
		try {
			Assert.hasLength(userName);
			Assert.hasLength(password);
			Assert.hasLength(newPassword);
		} catch (Throwable e) {
			e.printStackTrace();
			return ResetPasswordrReturnEnum.FAILED;
		}
		
		List<User> listUser = this.userDAO.retrieveByName(userName);
		if (listUser == null || listUser.isEmpty())
			return ResetPasswordrReturnEnum.USER_NOT_EXISTS;
		
		User user = listUser.get(0);
		if (!password.equals(user.getPassword())) 
			return ResetPasswordrReturnEnum.PASSWORD_NOT_MATCH;

		user.setPassword(newPassword);
		this.userDAO.update(user);
		return ResetPasswordrReturnEnum.SUCCESS;
	}

	public UserDAO getUserDAO() {
		return userDAO;
	}

	@Resource(name = "UserDAOImpl")
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
}
